package com.foo.DAO;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.sql.DataSource;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;

import com.foo.Entity.TickerInfoData;

public class SpatialDAOImpl implements SpatialDAO
{
	private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
	SqlParameterSource namedParameters =null;
	String query = "";
	TickerInfoData[] ticker =null;
	int size=0;

	public void setDataSource(DataSource dataSource) {
		this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
	}

	@Override
	public TickerInfoData[] selectForum(String sorttype,String value) 
	{
		try
		{
			if(sorttype.equals("Country"))
			{
				query = "select * from tickerinfo where country=:country";
				namedParameters = new MapSqlParameterSource("country", value);

			}
			if(sorttype.equals("State"))
			{
				query = "select * from tickerinfo where state=:state";
				namedParameters = new MapSqlParameterSource("state", value);
			}
			if(sorttype.equals("Industry"))
			{
				query = "select * from tickerinfo where industry=:industry";
				namedParameters = new MapSqlParameterSource("industry", value);
			}
			if(sorttype.equals("Sector"))
			{
				query = "select * from tickerinfo where sector_name=:sector";
				namedParameters = new MapSqlParameterSource("sector", value);
			}

			return (TickerInfoData[]) namedParameterJdbcTemplate.queryForObject(query,
					namedParameters, new RowMapper() {
				public Object mapRow(ResultSet resultSet, int rowNum)
				throws SQLException {
					int j=0;
					if (resultSet !=null)
					{
						resultSet.last();
						size=resultSet.getRow();
						ticker=new TickerInfoData[size];
						resultSet.beforeFirst();
					}
					while(resultSet.next())
					{
						TickerInfoData data = new TickerInfoData(resultSet.getInt(1),resultSet.getString(2),resultSet.getString(3),resultSet.getString(4),
								resultSet.getString(5),resultSet.getString(6),resultSet.getString(7),
								resultSet.getDouble(8));
						ticker[j]=data;
						j++;
					}
					return ticker;
				}
			});
		}
		catch(Exception e)
		{
			return null;
		}
	}

}
